<?php 
if(!defined('INSIDE')){
	exit("Access Denied");
}

class language{
	private static $P_SECTION = "/\s*\[(.+?)\]\s*/";
	private static $P_KEYVAL1 = "/\s*(\S+?)\s*=\s*\"(.+?)\"\s*/";
	private static $P_KEYVAL2 = "/\s*(\S+?)\s*=(.+?)$/";
	
	public static function load_lang_file($app){
		global $_GVAR;
		$langfile = util::file_abs('lang', $app);
		
		if($fp = fopen($langfile, 'r')){
			$section_nm = '';
			if(!array_key_exists($app, $_GVAR['langtext'])){
				$_GVAR['langtext'][$app] = array();
			}
			$applang = &$_GVAR['langtext'][$app]; 
			while (!feof($fp)) {
				$line = trim(fgets($fp));
				str_replace(array("\n", "\r"), "", $line);
				if(empty($line)){
					continue;
				}
				$match_res = array();
				if(preg_match(language::$P_SECTION, $line, $match_res) != 0){ //section found
					$section_nm = $match_res[1];
					continue;
				}
				elseif(preg_match(language::$P_KEYVAL1, $line, $match_res) != 0){ //key-val found
					if(empty($section_nm)){
						$applang[trim($match_res[1])]=$match_res[2];
					}
					else{
						$applang[$section_nm][trim($match_res[1])]=$match_res[2];
					}
					continue;
				}
				elseif(preg_match(language::$P_KEYVAL2, $line, $match_res) != 0){
					//key-val found
					if(empty($section_nm)){
						$applang[trim($match_res[1])]=$match_res[2];
					}
					else{
						$applang[$section_nm][trim($match_res[1])]=trim($match_res[2]);
					}
					continue;
				}
				else{
					continue;
				}
			}
			fclose($fp);
		}
		else{
			exit("Missing Language File: ".$app);
		}
	}
	
	public static function get_lang_var($var){
		// eg $var="theme/mem_frm_lbl_login"
		// eg $var="member/reguser/mem_frm_lbl_login" 
		$ret;
		$app;
		$mod_var;
		if(strpos($var, ":")!==false){
			$tmparr = explode(":", $var);
			$app = $tmparr[0];
			$mod_var = $tmparr[1];
		}
		else{
			$mod_var = $var;
		}
		if(empty($app)){
			$app = "theme";
		}
		global $_GVAR;
		if(!array_key_exists($app, $_GVAR['langtext'])){
			self::load_lang_file($app);
		}
		$fromvar = $_GVAR['langtext'][$app];
		
		$tmparr = explode("/", $mod_var);
// 		echo var_dump($tmparr)."<br/>";
		if(count($tmparr) == 1){
			$ret =  @$fromvar[trim($tmparr[0])];
		}
		elseif(count($tmparr) == 2){
			$ret =  @$fromvar[trim($tmparr[0])][trim($tmparr[1])];
		}
		if(empty($ret) || !is_string($ret)){
			$ret = '[missing_lang_var:'.$var.']';
		}
		return $ret;
	}
}
?>